package com.derbysoft.synxisadapter.action;

import com.derbysoft.core.web.BaseAction;
import com.derbysoft.synxisadapter.action.support.PaginalResult;
import com.derbysoft.synxisadapter.commons.utils.DateJsonValueProcessor;
import com.derbysoft.synxisadapter.commons.utils.ExceptionUtils;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * User: jason
 * Date: 2013-01-21
 */
@Results(value = {
        @Result(name = DMXAbstractAction.AJAX_RESULT, location = "/page/AjaxResult.ftl")
})
public abstract class DMXAbstractAction extends BaseAction {
    public static final String AJAX_RESULT = "AjaxResult";
    public static final String RESULT = "result";
    public static final String MESSAGE = "message";

    private String ajaxResult;

    protected PaginalResult dmxPaging(List<?> items, int page, long total) {
        return new PaginalResult(items, page, total);
    }

    protected String populateSucceededJsonResult(Object message, String... excludes) {
        return populateJsonResult(Boolean.TRUE, message, excludes);
    }

    protected String populateFailedJsonResult(Throwable throwable) {
        return populateJsonResult(Boolean.FALSE,
                String.format("%s: %s", throwable.getClass().getSimpleName(), ExceptionUtils.toString(throwable)));
    }

    private String populateJsonResult(Boolean result, Object message, String... excludes) {

        Map<String, Object> map = new HashMap<String, Object>();
        map.put(RESULT, result);
        map.put(MESSAGE, message);
        JsonConfig conf = new JsonConfig();
        conf.setExcludes(excludes);
        conf.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
        conf.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor());
        JSONObject jsonObject = JSONObject.fromObject(map, conf);
        ajaxResult = jsonObject.toString();
        return AJAX_RESULT;
    }

    public String getAjaxResult() {
        return ajaxResult;
    }
}
